package com.thewell79.areadiary.request;

import android.util.Log;

import com.android.volley.AuthFailureError;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.thewell79.areadiary.BaseApplication;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by THEWELL-LOBBY on 2015-04-22.
 */
public class PostStringRequest implements Response.Listener<String>, Response.ErrorListener {

    public interface OnReqeust {
        public void onLoading();
        public void onEndRequest(String response);
        public void onEnd(boolean isError, VolleyError error);
    }

    private int method;
    private String url;
    private HashMap<String, String> params = new HashMap<>();
    private OnReqeust onLoading;

    public PostStringRequest(int method, String url) {
        this.method = method;
        this.url = url;
    }

    private StringRequest request = new StringRequest(method, url, this, this) {
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            return getParams();
        }
    };

    public void setParams(HashMap<String, String> params) {
        this.params = params;
    }

    public void setItemParams(String key, String value) {
        params.put(key, value);
    }

    private HashMap<String, String> getParams() {
        return params;
    }

    public void clearParams() {
        params.clear();
    }

    public void setOnLoading(OnReqeust onReqeust) {
        this.onLoading = onReqeust;
    }

    public void commit() {

        if (onLoading != null) {
            onLoading.onLoading();
        }

        BaseApplication.getInstance().getQueue().add(request);
    }

    @Override
    public void onErrorResponse(VolleyError error) {
        error.printStackTrace();

        if (onLoading != null) {
            onLoading.onEnd(false, error);
        }
    }

    @Override
    public void onResponse(String response) {

        Log.v("RESPONSE", response);

        if (onLoading != null) {
            onLoading.onEndRequest(response);
            onLoading.onEnd(true, null);
        }
    }
}